package com.jh.fcsm.service.sys;

import com.jh.fcsm.common.redis.RedisUtil;
import com.jh.fcsm.constant.RedisConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginAttemptService {

    private static final int MAX_ATTEMPT = 10;
    private static final String LOGINATTEMPT = "stdp:login:";
    @Autowired
    private RedisUtil redisUtil;

    public void loginSucceeded(String key) {
        redisUtil.del(LOGINATTEMPT + key);
    }

    public void loginFailed(String key) {
        int attempts = 0;
        try {
            attempts = (Integer) redisUtil.get(LOGINATTEMPT + key);
        } catch (Exception e) {
            attempts = 0;
        }
        attempts++;
        redisUtil.set(LOGINATTEMPT + key, attempts, RedisConstant.REDIS_EXPIRE_TEN_MIN);
    }

    public boolean isBlocked(String key) {
        try {
            return (Integer) redisUtil.get(LOGINATTEMPT + key) >= MAX_ATTEMPT;
        } catch (Exception e) {
            return false;
        }
    }
}